package com.thot.timyag.core.pathwatch;

import java.util.HashMap;
import java.util.Map;
import java.util.Observer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.thot.timyag.config.properties.ThotProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yangjf
 * @time 2019-04-11 16:00
 * 用于管理路径监听者
 */
@Component
public class PathWatchHub {
    @Autowired
    private ThotProperties properties;

    public Map<String, PathWatcher> pathWatcherMap = new HashMap<>();

    public ExecutorService executorPool;

    public PathWatchHub() {
        init();
    }

    public void init() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("watch-pool-%d").build();
        //Common Thread Pool
        executorPool = new ThreadPoolExecutor(1, 5,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }


    public void registerWatch(String path, Observer observer) {
        if (pathWatcherMap.containsKey(path)) {
            PathWatcher pathWatcher = pathWatcherMap.get(path);
            pathWatcher.addObserver(observer);
        } else {
            PathWatcher pathWatcher = new PathWatcher(path, properties.getIntervalSecond());
            pathWatcher.addObserver(observer);
            pathWatcherMap.put(path, pathWatcher);
            //执行监控
            executorPool.submit(new Runnable() {
                @Override
                public void run() {
                    pathWatcher.doWatch();
                }
            });
        }
    }
}
